<template>
    <eui-background type="common">
        <eui-navbar ref="EuiNavBar" title="销售监测" :displayable="false" @onClickStore="clickStore" rightIcon=""
            rightIcon5="icon-shaixuan" :showPopup="false" @clickRight="clickNavbarRight" />
        <view class="footer-view" :style="{ height: listHeight + 'rpx' }">
            <scroll-view scroll-y="true" style="height: 100%">
                <eui-card title="销售总览" :titleDesc="`截止于 ${lastReqDate} 单位 ${uniTypeText}`">
                    <template v-slot:extra>
                        <view style="justify-content: flex-end;font-size: 26rpx;" @click="clickStore">
                            <span style="max-width: 200rpx; ">{{ sUserStoreName }} </span><span>></span>
                        </view>
                    </template>
                    <scroll-view
                        style="width:100%; -ms-overflow-style: none; scrollbar-width: thin; scrollbar-color: transparent transparent; "
                        scroll-x="true" show-scrollbar="false">
                        <eui-card-input v-model="formData.c_current_type" :range="currentTypeOpts" flexWrap="nowrap"
                            @buttonClick="currentTypeChange" titleWidth="0" placeholder="" h-padding="0"
                            alignType="left" type="radio" rightIconType="right" :showBottomLine="false" />
                    </scroll-view>
                    <view style="width: 100%; display: grid;grid-template-columns: 33.33% 33.33% 33.33%;padding: 4rpx;">
                        <stat-item title="销售金额" :value="currentSum.c_at_sale" :compareValue="compareSum.c_at_sale"
                            :compareTitle="compareTitle"></stat-item>
                        <stat-item title="来客数" :value="currentSum.c_sale_count" :precision="0"
                            :compareValue="compareSum.c_sale_count" :compareTitle="compareTitle"></stat-item>
                        <stat-item title="客单价(元)" :value="currentSum.c_atv" :compareValue="compareSum.c_atv"
                            :compareTitle="compareTitle"></stat-item>
                        <stat-item title="折扣金额" :value="currentSum.c_disc_value" :compareValue="compareSum.c_disc_value"
                            :compareTitle="compareTitle"></stat-item>
                        <stat-item title="毛利率%" :value="currentSum.c_gross_margin" method="rate"
                            :compareValue="compareSum.c_gross_margin" :compareTitle="compareTitle"></stat-item>
                        <stat-item title="毛利额" :value="currentSum.c_gross_profit"
                            :compareValue="compareSum.c_gross_profit" :compareTitle="compareTitle"></stat-item>
                    </view>
                    <view
                        style="margin: 20rpx 0rpx; font-size: 20rpx; background-color: #F9FAFC; padding: 10rpx; color: #888888">
                        <view style="width: 100%; display: flex; flex-wrap: wrap;">
                            <view style="flex-grow: 0;">
                                <text style="color:red">●</text>
                                比较日期数据时，请确保使用相同的日期范围或天数，以保持一致性</br>
                            </view>
                            <view style="flex-grow: 0;">
                                &nbsp;&nbsp;&nbsp;本期 {{ formData.c_sale_da.substring(5, 12) }}({{
                                    dayOfWeek(formData.c_sale_da) }}) 至
                                {{ formData.c_sale_da_en.substring(5, 12) }}({{ dayOfWeek(formData.c_sale_da_en) }});对期
                                {{ formData.c_sale_da2.substring(5, 12) }}({{ dayOfWeek(formData.c_sale_da2) }}) 至
                                {{ formData.c_sale_da2_en.substring(5, 12) }}({{ dayOfWeek(formData.c_sale_da2_en) }})
                            </view>
                            <view style="flex-grow: 0;">
                                <text style="color:red">●</text>
                                <text v-if="sysConfig.rentSaleIsRevenue">包含租赁销售金额</text>
                                <text v-if="!sysConfig.rentSaleIsRevenue">不包含租赁销售金额</text>
                            </view>
                        </view>
                    </view>
                </eui-card>
                <eui-card title="销售趋势" titleDesc="仅分析近七天数据">
                    <template v-slot:extra>
                        <view style="justify-content: flex-end;font-size: 26rpx;">
                            <eui-combox selectWidth="120rpx" v-model="formData.c_amount_type" valueColor="#666666"
                                backgroundColor="#F8F8F8" :border="false" :candidates="amountTypeOpts" fieldName="value"
                                @selectChange="onAmountTypeChange">
                            </eui-combox>
                        </view>
                    </template>
                    <eui-lime-chart :option="saleTrendChartOption" :chartStyle="saleTrendChartStyle" />
                </eui-card>
                <eui-card title="时段统计" topMargin="10">
                    <eui-lime-chart :option="salePeriodChartOption" :chartStyle="salePeriodChartStyle" />
                </eui-card>
                <eui-card title="销售占比">
                    <eui-card-input v-model="formData.c_type" :range="saleRateOpts" @buttonClick="saleRateTypeChange"
                        titleWidth="0" radioWidth="200" placeholder="" h-padding="0" alignType="left" type="radio"
                        rightIconType="right" :showBottomLine="false" />
                    <view
                        style="width: 100%;display: grid;grid-template-columns: 30% 70%;  flex-wrap: wrap; padding: 4rpx;">
                        <view>
                            <eui-lime-chart :option="saleRateChartOption" :chartStyle="saleRateChartStyle" />
                        </view>
                        <view class="rate-view">
                            <view v-for="(item, index) in saleRateData" class="rate-card" style="height: 90rpx;">
                                <view class="rate-card" style="display: grid;grid-template-columns: 10% 50% 40%;">
                                    <eui-uicons style="margin-top: 10rpx;" size='20' fontFamily="enjoyIcon5"
                                        customPrefix="icon-xuanze_shixin" :color="rateColor[index]" />
                                    <text
                                        style="margin-left: 8rpx;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                                        {{ item.title }}</text>
                                    <view style="margin-right: 2rpx;text-align: right;"
                                        :style="{ color: rateColor[index] }">{{ item.rate
                                        }}</view>
                                </view>
                                <view class="rate-card" style="display: grid;grid-template-columns: 10% 90%;">
                                    <eui-uicons style="margin-top: 3rpx;margin-left: -2rpx;" size='25'
                                        fontFamily="enjoyIcon5"
                                        :customPrefix="item.upOrDown ? 'icon-shuju-shangsheng' : 'icon-shuju-xiajiang'"
                                        :color="item.upOrDown ? '#FF4000' : '#00AD60'" />
                                    <text
                                        style="margin-left: 8rpx;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">{{
                                            numeral(item.value).format('0,0.00') }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view style="width: 100%;text-align: center; font-size: 24rpx;color: #919191 ;"
                        @click="clickDetail">查看全部 ></view>
                </eui-card>
                <eui-card title="门店排名" bottomMargin="20">
                    <template v-slot:extra>
                        <view style="justify-content: flex-end;font-size: 26rpx;" c
                            v-if="['2', '3'].includes(storeType)">
                            <span style="max-width: 200rpx; ">本店排名：{{ currentStoreRank }}</span>
                        </view>
                    </template>
                    <eui-card-input v-model="formData.c_rank_type" radioWidth="200" :range="storeRankOpts"
                        @buttonClick="rankTypeChange" titleWidth="0" placeholder="" h-padding="0" alignType="left"
                        type="radio" rightIconType="right" :showBottomLine="false"
                        v-if="!['0', '1'].includes(storeType)" />
                    <swiper class="swiper" circular :indicator-dots="true" :autoplay="false">
                        <swiper-item v-for="(data, index) in rankListSwiper" :key="index">
                            <view class="rate-view">
                                <view v-for="(item, index2) in data" :key="index2">
                                    <view class="rank-card" style="height: 100rpx;" :style="{ marginBottom: index === rankListSwiper.length - 1 ? ' 60rpx' : '' }">
                                        <view class="rank-card" style="display: grid;grid-template-columns: 90% 10%;">
                                            <text
                                                style="font-size: 28rpx;font-weight: 600; white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                                                {{ item.name }}</text>
                                            <view
                                                style="margin-right: 4rpx;font-size: 28rpx;font-weight: 600; text-align: right;"
                                                :style="{ color: item.rankIndex <= 3 ? '#FFA500' : '#919191' }">{{
                                                    item.rankIndex }}</view>
                                        </view>
                                        <view class="rank-card"
                                            style="display: grid;grid-template-columns: 18% 32% 50%;">
                                            <text
                                                style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">销售</text>
                                            <text :style="{ color: item.upOrDown ? 'red' : 'green' }">{{ item.rate
                                                }}</text>
                                            <text
                                                style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: right;">毛利
                                                {{ item.grossMargin }}</text>
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </swiper-item>
                    </swiper>
                </eui-card>
                <!-- <eui-card>
                    <eui-tab :tabs="tabData" tabStyle="margin: 0 100rpx" :value="tabIndex"
                        @change="tabChange" showBadge="true">
                    </eui-tab>
                    <eui-lime-chart :option="saleTrendChartOption" :chartStyle="saleTrendChartStyle" />
                </eui-card> -->
            </scroll-view>
        </view>
    </eui-background>
    <eui-popup ref="customPopup" background-color="#f8f8f8" type="bottom" :mask-click="true">
        <view class="popup-content">
            <view class="popup-title">筛选</view>
            <eui-card-input v-model="formData.c_unit_type" :range="unitTypeOpts" title="显示单位" placeholder=""
                h-padding="0" alignType="left" type="radio" />
            <eui-card-input v-model="formData.c_adno_level" :range="sysConfig.adnoLevel" title="部门层级" h-padding="0"
                alignType="left" type="radio" />
            <eui-card-input v-model="formData.c_class_level" :range="sysConfig.gdsclassLevel" title="品类层级" h-padding="0"
                alignType="left" type="radio" />
            <eui-card-input v-model="formData.c_day_period" :range="datePeriodOpts" radioWidth="180" title="今日/昨日"
                h-padding="0" alignType="left" type="radio" />
        </view>
        <view class="bt-button">
            <eui-button type="max" single-tag="reset" title="重置" @buttonClick="customClick" />
            <eui-button type="max" single-tag="fix" title="确定" @buttonClick="customClick" />
        </view>
    </eui-popup>
    <eui-datetime-rangePicker :value="formData.c_sale_da" :c_plan_begin_time="formData.c_sale_da"
        :c_require_complete_time="formData.c_sale_da_en" :timeIndex="timeIndex" :visible="showDatePicker"
        :model="dateModel" :yearsArr="yearsArr" :isDark="false" title="选择日期" @cancel="handCancel" @confirm="handConfirm"
        type="date" />

    <eui-datetime-rangePicker :value="formData.c_sale_da2" :c_plan_begin_time="formData.c_sale_da2"
        :c_require_complete_time="formData.c_sale_da2_en" :timeIndex="timeIndex" :visible="showDatePicker2"
        :model="dateModel" :yearsArr="yearsArr" :isDark="false" title="选择日期" @cancel="handCancel"
        @confirm="handConfirm2" type="date" />

    <eui-popup ref="searchPopup" background-color="#f8f8f8" type="bottom" :mask-click="true">
        <view class="popup-content">
            <view class="popup-title">自定义日期</view>
            <view class="m-card-input-view2">
                <view class="m-card-input-title2">
                    <text class="m-title-text2">本期日期</text>
                </view>
                <view class="time-view" @click="chooseTime(0)">
                    <text class="time-top">{{ formData.c_sale_da }}</text>
                </view>
                <view class="heng-view" />
                <view class="time-view" @click="chooseTime(1)">
                    <text class="time-top">{{ formData.c_sale_da_en }}</text>
                </view>
            </view>
            <view class="m-card-input-view2">
                <view class="m-card-input-title2">
                    <text class="m-title-text2">对期日期</text>
                </view>
                <view class="time-view" @click="chooseTime2(0)">
                    <text class="time-top">{{ formData.c_sale_da2 }}</text>
                </view>
                <view class="heng-view" />
                <view class="time-view" @click="chooseTime2(1)">
                    <text class="time-top">{{ formData.c_sale_da2_en }}</text>
                </view>
            </view>
        </view>
        <view class="bt-button">
            <eui-button type="max" single-tag="reset" title="重置" @buttonClick="buttonClick" />
            <eui-button type="max" single-tag="fix" title="确定" @buttonClick="buttonClick" />
        </view>
    </eui-popup>
</template>

<script setup type="ts">
import { onMounted, ref, reactive, computed, watch } from "vue";
import service from "@/common/service";
import { getRdsUrl, rdsRequest, } from '@/hooks/rdsServices';
import { onLoad } from "@dcloudio/uni-app";
import { init, getRdsSysConfig } from '@/hooks/init';
import { validateStores, validateGds, defaultMapping, validateStoresAndWno } from '@/hooks/useValidateMethod';
import StatItem from "./StatItem.vue";
import { useMainStore } from "@/store/modules/store";
import Enjoy from "@/common/enjoy";
import dayjs from 'dayjs';
import { getRelatedName, getUserDictName } from '../components/RelatedName.js';
import { useProRelatedNameHook } from '@/hooks/useProRelatedName';
import numeral from 'numeral';
const { mapChannel } = useProRelatedNameHook();
const rdsUrl = getRdsUrl();
const mainStore = useMainStore();

const searchPopup = ref(null);
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const listHeight = ref(300);
const oriHeight = ref(300);

const customPopup = ref(null);

const currentDetail = ref([])
const compareDetail = ref([])
dayjs.locale({
    ...dayjs.Ls['en'], // 以英文本地化配置为基础
    weekStart: 1 // 将每周的起始日设置为周一（0 代表周日，1 代表周一）
});
const showDatePicker = ref(false);
const showDatePicker2 = ref(false);
const dateModel = ref(['year', 'month', 'day']);
const yearsArr = ref([dayjs().year() - 10, dayjs().year()]);
const timeIndex = ref(0);
// 选择时间-取消
const handCancel = () => {
    showDatePicker.value = false;
    showDatePicker2.value = false;
}
// 选择时间-确认
const handConfirm = (time1, time2) => {
    showDatePicker.value = false;
    if (time2 < time1) {
        formData.value.c_sale_da = time2.substring(0, 10);
        formData.value.c_sale_da_en = time2.substring(0, 10);
        return;
    }
    if (time1) {
        formData.value.c_sale_da = time1.substring(0, 10);
    }
    if (time2) {
        formData.value.c_sale_da_en = time2.substring(0, 10);
    }
}
// 选择时间-确认
const handConfirm2 = (time1, time2) => {
    showDatePicker2.value = false;
    if (time2 < time1) {
        formData.value.c_sale_da2 = time2.substring(0, 10);
        formData.value.c_sale_da2_en = time2.substring(0, 10);
        return;
    }
    if (time1) {
        formData.value.c_sale_da2 = time1.substring(0, 10);
    }
    if (time2) {
        formData.value.c_sale_da2_en = time2.substring(0, 10);
    }
}
// 选择时间
const chooseTime = (index) => {
    timeIndex.value = index;
    setTimeout(() => {
        showDatePicker.value = true;
    }, 200)
}
const chooseTime2 = (index) => {
    timeIndex.value = index;
    setTimeout(() => {
        showDatePicker2.value = true;
    }, 200)
}
const storeType = ref('0');
const updateStoreType = async () => {
    const result = await validateStores(
        { fieldName: 'c_store_id', newValue: formData.value.c_store_id },
        { ischecklimit: true, firstValueMode: true }
    );
    storeType.value = result?.c_type || 0;
    saleRateOpts[0].disabled = !['0', '1'].includes(storeType.value)
    formData.value.c_type = ['0', '1'].includes(storeType.value) ? '8' : '2';
}

onMounted(async () => {
    await updateStoreType();
})
// 查询表单
const formData = ref({
    c_current_type: '1',
    c_sale_da: dayjs().format('YYYY-MM-DD'),
    c_sale_da_en: dayjs().format('YYYY-MM-DD'),
    c_sale_da2: dayjs().subtract(1, 'days').format('YYYY-MM-DD'),//对期
    c_sale_da2_en: dayjs().subtract(1, 'days').format('YYYY-MM-DD'),//对期
    c_is_compare: true,  //比上周
    c_type: '8', //1-机构, 2-部门, 3-品类
    c_level: 1,
    c_adno_level: 1, //部门层级
    c_class_level: 1, //品类层级
    c_store_id: mainStore.loginInfo.sUserStore,
    c_p_id: '',
    c_unit_type: '1',
    c_amount_type: 'c_at_sale',
    c_rank_type: '1',//排名类型
    c_day_period: '1',//昨日全天
})
const tabData = ref([{ name: '促销分析' }, { name: '新品分析' }]);

const tabIndex = ref(0);

const tabChange = async (value) => {
    tabIndex.value = value;
}

// 单位类型
const unitTypeOpts = reactive([
    { text: '元', value: '1' },
    { text: '万元', value: '2' }
])
const uniTypeText = computed(() => `${unitTypeOpts.find(f => f.value == formData.value.c_unit_type)?.text}`)


const datePeriodOpts = reactive([
    { text: '昨日全天', value: '1' },
    { text: '昨日同时段', value: '2' }
])
const datePeriodText = computed(() => `${datePeriodOpts.find(f => f.value == formData.value.c_date_period)?.text}`)


const amountTypeOpts = reactive([
    { text: '销售额', value: 'c_at_sale' },
    { text: '交易数', value: 'c_sale_count' },
    { text: '毛利额', value: 'c_gross_profit' },
    { text: '毛利率', value: 'c_gross_margin' }
])

// 顶部统计
const currentTypeOpts = reactive([
    { text: '今日/昨日', value: '1' },
    { text: '本周/上周', value: '2' },
    { text: '本月/上月', value: '3' },
    { text: '自定义', value: '4' }
])
const currentTitle = computed(() => `${currentTypeOpts.find(f => f.value == formData.value.c_current_type)?.text}销售`)


const saleRateOpts = reactive([
    { text: '分区', value: '8', disabled: false },
    // { text: '渠道', value: '6' },
    { text: '部门', value: '2' },
    { text: '品类', value: '3' }
])
const saleRateChartTitle = computed(() => `${saleRateOpts.find(f => f.value == formData.value.c_type)?.text}占比`)

// 顶部统计
const storeRankOpts = reactive([
    { text: '同业态', value: '1' },
    { text: '同分区', value: '2' },
    { text: '同店群', value: '3' }
])
const storeRankChartTitle = computed(() => `${storeRankOpts.find(f => f.value == formData.value.c_type)?.text}排名`)

const compareTitle = computed(() => {
    const name = currentTypeOpts.find(f => f.value == formData.value.c_current_type)?.text;
    let chartName = name.split('/')[1];
    if (formData.value.c_current_type === '4') {
        chartName = '对期';
    }
    return chartName;
})

const dayOfWeek = (value) => {
    if (value) {
        const dayIndex = dayjs(value).day();
        const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return daysOfWeek[dayIndex];
    }
    return '';
}

// 变更时间类型
const currentTypeChange = async (value) => {
    if (value === '1') {
        //今日
        formData.value.c_sale_da = dayjs().format('YYYY-MM-DD');
        formData.value.c_sale_da_en = dayjs().format('YYYY-MM-DD');
        //昨日
        formData.value.c_sale_da2 = dayjs().subtract(1, 'days').format('YYYY-MM-DD');
        formData.value.c_sale_da2_en = dayjs().subtract(1, 'days').format('YYYY-MM-DD');
    } else if (value === '2') {
        // 获取本周的第一天
        let firstDay = dayjs().startOf('week').format('YYYY-MM-DD');
        // 获取今天的日期
        let today = dayjs().format('YYYY-MM-DD');

        formData.value.c_sale_da = firstDay;
        formData.value.c_sale_da_en = today;
        //上周开始
        formData.value.c_sale_da2 = dayjs(firstDay).subtract(1, 'weeks').format('YYYY-MM-DD');
        //上周结束
        formData.value.c_sale_da2_en = dayjs(today).subtract(1, 'weeks').format('YYYY-MM-DD');
    } else if (value === '3') {
        // 获取本月的第一天
        let firstDay = dayjs().startOf('month').format('YYYY-MM-DD');
        // 获取今天的日期
        let today = dayjs().format('YYYY-MM-DD');

        formData.value.c_sale_da = firstDay;
        formData.value.c_sale_da_en = today;

        //上月开始
        formData.value.c_sale_da2 = dayjs(firstDay).subtract(1, 'months').format('YYYY-MM-DD');
        //上月结束
        formData.value.c_sale_da2_en = dayjs(today).subtract(1, 'months').format('YYYY-MM-DD');
    } else if (value === '4') {
        searchPopup.value.open();
        return;
    }

    // resetCompareDate();
    await searchData();
}

const saleRateTypeChange = async (value) => {
    service.enjoyShowLoading("正在加载...");
    if (value == '2') {
        formData.value.c_level = formData.value.c_adno_level;
    } else if (value == '3') {
        formData.value.c_level = formData.value.c_class_level;
    }
    formData.value.c_type = value;
    await querySaleRate();
    service.enjoyHideLoading();
}
const rankTypeChange = async (value) => {
    formData.value.c_rank_type = value;
    service.enjoyShowLoading("正在加载...");
    await querySaleStoreRank();
    service.enjoyHideLoading();
}
const saleTrendChartDataY = ref([])
const saleTrendChartDataX = ref([]);
const saleTrendChartStyle = ref("height: 400rpx;background: #FFFFFF");
const saleTrendChartOption = computed(() => {
    return {
        title: {
            text: ''
        },
        color: ['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
        tooltip: {
            trigger: 'axis',
            confine: true,
            triggerOn: 'click',
        },
        legend: {
            top: '0%',
            itemHeight: 8,
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '10%',
            containLabel: true,
        },
        xAxis: {
            splitLine: {
                show: false // 不显示网格线
            },
            axisTick: {
                show: false // 不显示坐标轴刻度线
            },
            axisLine: {
                show: false, // 不显示坐标轴线
            },
            axisLabel: {
                rotate: 45
            },
            type: 'category',
            data: saleTrendChartDataX.value
        },
        yAxis: {
            type: 'value',
            axisTick: {
                show: false // 不显示坐标轴刻度线
            },
            axisLine: {
                show: false, // 不显示坐标轴线
            }
        },
        series: saleTrendChartDataY.value,
    }
});

const salePeriodChartDataY = ref([])
const salePeriodChartDataX = ref([]);
const salePeriodChartStyle = ref("height: 450rpx;background: #FFFFFF");
const salePeriodChartOption = computed(() => {
    return {
        title: {
            text: ''
        },
        color: ['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
        tooltip: {
            trigger: 'axis',
            confine: true,
            triggerOn: 'click',
        },
        legend: {
            top: '0%',
            itemHeight: 8,
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '10%',
            containLabel: true,
        },
        xAxis: {
            splitLine: {
                show: false // 不显示网格线
            },
            axisTick: {
                show: false // 不显示坐标轴刻度线
            },
            axisLine: {
                show: false, // 不显示坐标轴线
            },
            type: 'category',
            data: salePeriodChartDataX.value
        },
        yAxis: {
            type: 'value',
            axisTick: {
                show: false // 不显示坐标轴刻度线
            },
            axisLine: {
                show: false, // 不显示坐标轴线
            }
        },
        series: salePeriodChartDataY.value,
    }
});

const saleRateChartDataY = ref([])
const saleRateChartDataX = ref([]);
const saleRateChartStyle = ref("height: 300rpx;background: #FFFFFF");
const rateColor = ref(['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']);
const saleRateChartOption = computed(() => {
    return {
        title: {
            text: saleRateChartTitle.value,
            bottom: '0%',
            left: '15%',
            textStyle: {
                fontSize: 12,
                color: '#666666'
            }
        },
        // grid: {
        //     left: '3%',
        //     right: '4%',
        //     bottom: '3%',
        //     top: '4%',
        //     containLabel: true,
        // },
        color: ['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
        // tooltip: {
        //     trigger: 'item',
        //     confine: true,
        //     triggerOn: 'click',
        //     padding: 10,
        // },
        legend: {
            show: false,
            top: '0%',
            left: 'center'
        },
        series: saleRateChartDataY.value,
    }
});

const lastReqDate = computed(() => {
    currentPeriod.value = currentPeriod.value;
    return dayjs().format('MM-DD hh:mm');
})

// 查询数据接口
const searchData = async () => {
    service.enjoyShowLoading('正在加载...');
    //销售总览
    queryCurSale();
    //销售趋势
    querySaleTrend();
    //销售占比
    querySaleRate();
    //销售排名
    querySaleStoreRank();
    //时段数据
    querySalePeriod();
    setTimeout(() => {
        service.enjoyHideLoading();
    }, 2000)
}

//销售总览
const currentData = ref([])
const compareData = ref([])
const queryCurSale = async () => {
    const objectData = {
        c_sale_da: formData.value.c_sale_da,
        c_sale_da_en: formData.value.c_sale_da_en,
        c_sale_da2: formData.value.c_sale_da2,
        c_sale_da2_en: formData.value.c_sale_da2_en,
        c_store_id: formData.value.c_store_id,
        c_type: '1',
        c_is_compare: true,
    };
    let methodName = 'QueryCurSaleMBM';
    //时段查询
    if (formData.value.c_day_period == '2' && formData.value.c_current_type == '1') {
        methodName = 'QueryCurSalePeriodMBM';
    }
    const result = await rdsRequest(rdsUrl.scApi, '实时销售监测', methodName, objectData, '881',);
    currentData.value = result?.currentData;
    compareData.value = result?.compareData;
}

//销售趋势（近七天）
const saleTrendData = ref([]);
const querySaleTrend = async () => {
    const saletRendReq = {
        ...formData.value,
        c_sale_da: dayjs().subtract(7, 'days').format('YYYY-MM-DD'),
        c_sale_da_en: dayjs().subtract(1, 'days').format('YYYY-MM-DD'),
        c_sale_da2: dayjs().subtract(7, 'days').format('YYYY-MM-DD'),
        c_sale_da2_en: dayjs().subtract(1, 'days').format('YYYY-MM-DD'),
        c_store_id: formData.value.c_store_id,
        c_type: '7',
    }
    let methodName = 'QueryCurSaleMBM';
    //时段查询
    if (formData.value.c_day_period == '2' && formData.value.c_current_type == '1') {
        methodName = 'QueryCurSalePeriodMBM';
    }
    const saleTrendResult = await rdsRequest(rdsUrl.scApi, '实时销售监测', methodName, saletRendReq, '881');
    saleTrendData.value = saleTrendResult.currentData;
    await formatSaleTrendData(saletRendReq);
}

//销售占比
const currentRateData = ref(0);
const compareRateData = ref(0);
const querySaleRate = async () => {
    const saletRateReq = {
        ...formData.value,
        c_store_id: formData.value.c_type != '1' ? '' : formData.value.c_store_id,
        c_type: formData.value.c_type,
        c_level: formData.value.c_level,
    }
    let methodName = 'QueryCurSaleMBM';
    // if (saletRateReq.c_type == '8' && ['2', '3'].includes(storeType.value)) {
    //     saletRateReq.c_type = '6';
    //     saletRateReq.c_level = formData.value.c_adno_level;
    //     formData.value.c_type = '6';
    // }
    if (saletRateReq.c_type == '8') {
        methodName = "QueryCurSaleRateRegion"
    }
    //时段查询
    if (formData.value.c_day_period == '2' && formData.value.c_current_type == '1') {
        methodName = 'QueryCurSalePeriodMBM';
    }
    if (formData.value.c_type == '2') {
        saletRateReq.c_level = formData.value.c_adno_level;
    } else if (formData.value.c_type == '3') {
        saletRateReq.c_level = formData.value.c_class_level;
    }
    const saleRateResult = await rdsRequest(rdsUrl.scApi, '实时销售监测', methodName, saletRateReq, '881');
    currentRateData.value = saleRateResult?.currentData;
    compareRateData.value = saleRateResult?.compareData;
    await formatSaleRateData(saletRateReq.c_type);
}

const currentRankData = ref([]);
const compareRankData = ref([]);
//销售排名
const querySaleStoreRank = async () => {
    const objectData = {
        c_sale_da: formData.value.c_sale_da,
        c_sale_da_en: formData.value.c_sale_da_en,
        c_sale_da2: formData.value.c_sale_da2,
        c_sale_da2_en: formData.value.c_sale_da2_en,
        c_store_id: formData.value.c_store_id,
        c_type: formData.value.c_rank_type,
        c_is_compare: true,
    };
    if (['0', '1'].includes(storeType.value)) {
        objectData.c_type = '';
    }

    const result = await rdsRequest(rdsUrl.scApi, '实时销售监测', 'QueryCurSaleStoreRank', objectData, '881');
    currentRankData.value = result?.currentData;
    compareRankData.value = result?.compareData;
    await formatSaleRankData();
}
//时段数据
const currentPeriod = ref([])
const comparePeriod = ref([])
const querySalePeriod = async () => {
    const objectData = {
        ...formData.value,
        c_level: '',
        c_p_id: '',
        c_sale_da: formData.value.c_sale_da,
        c_sale_da_en: formData.value.c_sale_da_en,
        c_sale_da2: formData.value.c_sale_da2,
        c_sale_da2_en: formData.value.c_sale_da2_en,
        c_store_id: formData.value.c_store_id,
        c_type: '1',
        c_is_compare: true
    }
    //时段数据
    const result = await rdsRequest(rdsUrl.scApi, '实时销售监测', 'FetchPeriodData', objectData, '881');
    currentPeriod.value = result?.filter(f => f.c_date_type == '1') || [];
    comparePeriod.value = result?.filter(f => f.c_date_type == '2') || [];
    await formatSalePeriodData();
}

const formatSaleTrendData = async () => {
    saleTrendChartDataY.value = [];
    const amountType = formData.value.c_amount_type || 'c_at_sale';

    let startDate = dayjs().subtract(7, 'days').format('YYYY-MM-DD');
    let endDate = dayjs().subtract(1, 'days').format('YYYY-MM-DD');
    let dateRange = [];
    let currentDate = dayjs(startDate);
    while (currentDate.isSame(endDate, 'day') || currentDate.isBefore(endDate, 'day')) {
        dateRange.push(currentDate.format('YYYY-MM-DD'));
        currentDate = currentDate.add(1, 'day');
    }

    let sum = 0;

    const saleTrendItem = dateRange?.map(x => {
        const item = saleTrendData.value.find(y => y.c_id.substring(0, 10) === x)
        if (item) {
            const data = calcUnit(item);
            sum += data[amountType];
            return data[amountType].toFixed(2);
        } else {
            return 0;
        }
    });
    const saleDateList = dateRange?.map(x => { return x.substring(5, 10) });
    saleTrendChartDataX.value = [...saleDateList];

    // 计算平均值
    // const sum = saleTrendItem.reduce((p, v) =>  p + v, 0);
    const saleTrendAvg = Array(saleTrendItem.length).fill((sum / 7).toFixed(2));
    saleTrendChartDataY.value.push({
        name: amountTypeOpts.find(f => f.value == amountType)?.text,
        type: 'line',
        smooth: true,//平滑曲线
        showSymbol: false,//不显示点
        emphasis: {
            focus: 'none',
            disabled: true,
        },
        data: saleTrendItem,
        barWidth: '100%',
        label: {
            show: true, // 显示标签
            position: ['50%', '50%'], // 标签位置
            color: "#FFFFFF",
            lineHeight: 12,
            fontSize: 10,
            fontWeight: 100,
            align: 'center',
            verticalAlign: 'middle'
        }
    })
    saleTrendChartDataY.value.push({
        name: '平均值',
        type: 'line',
        smooth: true,
        showSymbol: false,
        emphasis: {
            focus: 'none',
            disabled: true,
        },
        data: saleTrendAvg,
        barWidth: '100%',
        lineStyle: {
            type: 'dashed' //虚线
        },
        label: {
            show: true, // 显示标签
            position: ['50%', '50%'], // 标签位置
            color: "#FFFFFF",
            lineHeight: 12,
            fontSize: 10,
            fontWeight: 100,
            align: 'center',
            verticalAlign: 'middle'
        }
    })

}

const formatSalePeriodData = async () => {
    salePeriodChartDataY.value = [];
    const amountType = formData.value.c_amount_type || 'c_at_sale';
    let ids = [...currentPeriod.value?.map(f => f.c_tp_id), ...comparePeriod.value?.map(f => f.c_tp_id)];
    ids = ids.filter((f, index) => ids.indexOf(f) == index);
    const list = ids.map(id => {
        const current = currentPeriod.value.find(f => f.c_tp_id == id);
        const compare = comparePeriod.value.find(f => f.c_tp_id == id);
        const period = current?.c_period || compare?.c_period || '';
        return {
            title: period.split('-')[1] || '',
            current: calcUnit(current || { ...defaultSum }),
            compare: calcUnit(compare || { ...defaultSum })
        }
    })
    salePeriodChartDataX.value = list.map(x => { return x.title });

    const name = currentTypeOpts.find(f => f.value == formData.value.c_current_type)?.text
    let chartName = name.split('/');
    if (formData.value.c_current_type === '4') {
        chartName = [`${formData.value.c_sale_da.substring(5, 10)}~${formData.value.c_sale_da_en.substring(5, 10)}`, `${formData.value.c_sale_da2.substring(5, 10)}~${formData.value.c_sale_da2_en.substring(5, 10)}`]
    }

    salePeriodChartDataY.value.push({
        name: chartName[0],
        type: 'line',
        smooth: true,//平滑曲线
        showSymbol: false,//不显示点
        emphasis: {
            focus: 'none',
            disabled: true,
        },
        data: list.map(x => x.current?.[amountType].toFixed(2)),
        barWidth: '100%',
        label: {
            show: true, // 显示标签
            position: ['50%', '50%'], // 标签位置
            // 可以通过 formatter 自定义标签格式
            // formatter: bcnameList[i] + '\n' + '{c}' + '%', // {c} 表示数据值
            color: "#FFFFFF",
            lineHeight: 12,
            fontSize: 10,
            fontWeight: 100,
            align: 'center',
            verticalAlign: 'middle'
        }
    })
    salePeriodChartDataY.value.push({
        name: chartName[1],
        type: 'line',
        smooth: true,
        showSymbol: false,
        emphasis: {
            focus: 'none',
            disabled: true,
        },
        data: list.map(x => x.compare?.[amountType].toFixed(2)),
        barWidth: '100%',
        label: {
            show: true, // 显示标签
            position: ['50%', '50%'], // 标签位置
            color: "#FFFFFF",
            lineHeight: 12,
            fontSize: 10,
            fontWeight: 100,
            align: 'center',
            verticalAlign: 'middle'
        }
    })

}

const saleRateData = ref([]);
const formatSaleRateData = async (type) => {
    saleRateChartDataY.value = [];
    const amountType = formData.value.c_amount_type || 'c_at_sale';
    let ids = [...currentRateData.value?.map(f => f.c_id), ...compareRateData.value?.map(f => f.c_id)];
    ids = ids.filter((f, index) => ids.indexOf(f) == index);
    let classType = 'rdsStores';
    if (type == '2') {
        classType = 'rdsDeparts';
    }
    else if (type == '3') {
        classType = 'rdsGdsclasses';
    } else if (type == '8') {
        classType = 'rdsStores';
    }

    const list = ids.map(id => {
        const current = currentRateData.value.find(f => f.c_id == id);
        const compare = compareRateData.value.find(f => f.c_id == id);
        return {
            title: type == '6' ? mapChannel.value[id] || id || "其它" : getRelatedName(classType, id) || id || "其它",
            current: calcUnit(current || { ...defaultSum }),
            compare: calcUnit(compare || { ...defaultSum })
        }
    })

    const currentSum = calcSum(currentRateData.value);
    const compareSum = calcSum(compareRateData.value);

    saleRateChartDataX.value = list.map(x => { return x.title });

    saleRateData.value = list.map(x => {
        return {
            name: x.title,
            title: x.title,
            value: x.current[amountType],
            compareValue: x.compare[amountType],
            rate: (((x.current[amountType] / currentSum[amountType]) * 10000) / 100).toFixed(2) + '%',
            upOrDown: x.current[amountType] - x.compare[amountType] > 0 ? true : false,
        }
    })

    // 按 value 降序排序
    saleRateData.value.sort((a, b) => b.value - a.value);
    const otherIndex = saleRateData.value.findIndex(item => item.name === "其它");

    if (saleRateData.value.length > 6) {
        let additionalValue = 0;
        // 计算下标大于 6 的元素的总和
        for (let i = 5; i < saleRateData.value.length; i++) {
            additionalValue += saleRateData.value[i].value;
        }
        if (otherIndex !== -1) {
            saleRateData.value[otherIndex].value += additionalValue;
        } else {
            saleRateData.value.push({ "name": "其它", "title": "其它", "rate": 0, "upOrDown": true, "value": additionalValue });
        }
        // 移除下标大于 6 的元素（除了 "其它" 元素）
        saleRateData.value.splice(5, saleRateData.value.length - 5 - 1);

    }
    const otherElement = saleRateData.value.splice(otherIndex !== -1 ? otherIndex : saleRateData.value.length - 1, 1)[0];
    if (otherElement) {
        const rate = (((otherElement.value / currentSum[amountType]) * 10000) / 100).toFixed(2) + '%';
        const otherCompareSum = saleRateData.value.reduce((p, v) => p + v.compareValue, 0);
        const otherCompare = compareSum[amountType] - otherCompareSum;
        saleRateData.value.push({ ...otherElement, rate: rate, upOrDown: otherElement.value - otherCompare > 0 });
    }

    // 计算数据总和
    var totalValue = saleRateData.value.reduce((sum, item) => sum + item.value, 0);

    saleRateChartDataY.value.push({
        name: currentSum[amountType],
        type: 'pie',
        radius: ['30%', '70%'],
        center: ['40%', '40%'], // 圆心位置
        avoidLabelOverlap: false,
        label: {
            show: false,
            position: 'center',
            fontSize: 10,
            formatter: '{b}: {c}'
        },
        emphasis: {
            label: {
                show: true,
                fontSize: 10,
                fontWeight: 'bold',
                formatter: function (param) {
                    return param.value.toFixed(2)// + '\n' + param.percent + '%';
                },
            }
        },
        labelLine: {
            show: false
        },
        data: saleRateData.value,
    })
}

const currentStoreRank = ref('1');
const rankListSwiper = ref([]);
const formatSaleRankData = async () => {
    rankListSwiper.value = [];
    const amountType = 'c_at_sale';

    let ids = [...currentRankData.value?.map(f => f.c_store_id), ...compareRankData.value?.map(f => f.c_store_id)];
    ids = ids.filter((f, index) => ids.indexOf(f) == index);

    const list = ids.map(x => {
        const current = currentRankData.value.find(f => f.c_store_id == x);
        const compare = compareRankData.value.find(f => f.c_store_id == x);
        return {
            title: getRelatedName("rdsStores", x) || x,
            current: calcUnit(current || { ...defaultSum }),
            compare: calcUnit(compare || { ...defaultSum })
        }
    })

    list.sort((a, b) => b.current[amountType] - a.current[amountType]);

    const saleRankData = list.map((x, index) => {
        return {
            name: x.title,
            storeId: x.current.c_store_id,
            rankIndex: index + 1,
            value: x.current[amountType],
            compareValue: x.compare[amountType],
            rate: x.compare[amountType] == 0 ? '100%' : (Math.round(((x.current[amountType] - x.compare[amountType]) / x.compare[amountType]) * 10000) / 100).toFixed(1) + '%',
            // rate: (x.current[amountType] - x.compare[amountType]) / x.current[amountType],
            grossMargin: (x.current.c_gross_margin - x.compare.c_gross_margin).toFixed(1) + '%',
            upOrDown: ((x.current[amountType] - x.compare[amountType]) / x.compare[amountType]) * 100 > 0 ? true : false,
        }
    })
    for (var i = 0; i < saleRankData.length; i += 6) {
        rankListSwiper.value.push(saleRankData.slice(i, i + 6));
    }
    currentStoreRank.value = saleRankData.find(x => x.storeId == sUserStore.value)?.rankIndex || '1';

}

const onAmountTypeChange = async (value) => {
    await formatSaleTrendData();
    await formatSalePeriodData();
}
const getCodeRuleLevel = async (c_type) => {
    // 获取部门层级
    // c_type === 'adno' : 'gdsclass';
    let result = [];
    const length = await rdsRequest(rdsUrl.scApi, '实时销售监测', 'GetCodeRuleLevel', c_type);
    if (length >= 0) {
        result = Array.from({ length: length }, (_, i) => ({ text: i + 1, value: i + 1 }));
    }
    return result;
}

// 获取系统参数、字典
const getSysConfig = async () => {
    sysConfig.value.adnoLevel = await getCodeRuleLevel('adno');
    sysConfig.value.adnoLevel.map(f => f.text = getUserDictName('部门层级', f.value + ''));
    sysConfig.value.gdsclassLevel = await getCodeRuleLevel('gdsclass');
    sysConfig.value.gdsclassLevel.map(f => f.text = getUserDictName('品类层级', f.value + ''));
    sysConfig.value.rentSaleIsRevenue = await getRdsSysConfig("进销存管理参数", "租赁商品销售是否记入销售收入") == '1';
}
// 设置默认值
const setDefault = async () => {
    const { loginInfo } = mainStore;
    sUserStore.value = loginInfo.sUserStore;
    sUserStoreName.value = loginInfo.sUserStoreName;
    sUser.value = loginInfo.sUser;
    formData.value.c_store_id = loginInfo.sUserStore;
}

onLoad(async (option) => {
    const jsonData = service.getLocalStorage("curSaleFormData");
    if (jsonData) {
        formData.value.c_unit_type = jsonData.c_unit_type;
        formData.value.c_adno_level = jsonData.c_adno_level;
        formData.value.c_class_level = jsonData.c_class_level;
    }
    await init();
    await getSysConfig();
    await setDefault();
    await searchData();
})

const defaultSum = {
    c_at_sale_rate: 0,
    c_at_sale: 0,
    c_sale_value: 0,
    c_atv: 0,
    c_sale_count: 0,
    c_gross_profit: 0,
    c_gross_margin: 0,
    c_disc_value: 0
}

const calcSum = (items) => {
    const sum = (items || []).reduce((p, v) => {
        return {
            c_at_sale: p.c_at_sale + v.c_at_sale,
            c_sale_value: p.c_sale_value + v.c_sale_value,
            c_atv: 0,
            c_sale_count: p.c_sale_count + v.c_sale_count,
            c_gross_profit: p.c_gross_profit + v.c_gross_profit,
            c_gross_margin: p.c_gross_margin + v.c_gross_margin,
            c_disc_value: p.c_disc_value + v.c_disc_value
        }
    }, { ...defaultSum });
    const unit = formData.value.c_unit_type == '1' ? 1 : 10000;

    sum.c_gross_margin = sum.c_at_sale == 0 ? 0 : sum.c_gross_profit / sum.c_at_sale * 100;
    sum.c_atv = sum.c_sale_count == 0 ? 0 : sum.c_at_sale / sum.c_sale_count;
    sum.c_at_sale = sum.c_at_sale / unit;
    sum.c_sale_value = sum.c_sale_value / unit;
    sum.c_gross_profit = sum.c_gross_profit / unit;
    sum.c_disc_value = sum.c_disc_value / unit;
    return sum;
}

const currentSum = computed(() => {
    return calcSum(currentData.value);
})


const compareSum = computed(() => {
    return calcSum(compareData.value);
})

const calcUnit = (item) => {
    const sum = { ...item }
    const unit = formData.value.c_unit_type == '1' ? 1 : 10000;
    sum.c_atv = sum.c_atv;
    sum.c_at_sale = sum.c_at_sale / unit;
    sum.c_sale_value = sum.c_sale_value / unit;
    sum.c_gross_profit = sum.c_gross_profit / unit;
    sum.c_disc_value = sum.c_disc_value / unit;
    return sum;
}

const customClick = async (e) => {
    const { singleTag, modelValue, type } = e;
    switch (singleTag) {
        case 'reset':
            formData.value = {
                ...formData.value,
                c_current_type: '1', //本期
                c_sale_da: dayjs().format('YYYY-MM-DD'),
                c_sale_da_en: dayjs().format('YYYY-MM-DD'),
                c_sale_da2: dayjs().format('YYYY-MM-DD'),//对期
                c_sale_da2_en: dayjs().format('YYYY-MM-DD'),//对期
                c_is_compare: true,
                c_type: '1', //1-机构, 2-部门, 3-品类
                c_level: 1,
                c_store_id: mainStore.loginInfo.sUserStore,
                c_p_id: '',
                c_adno_level: 1,
                c_class_level: 1,
                c_unit_type: '1',
            };
            service.removeStorageSync('curSaleFormData');
            service.addlocalStorage('curSaleFormData', { c_unit_type: formData.value.c_unit_type, c_adno_level: formData.value.c_adno_level, c_class_level: formData.value.c_class_level, c_day_period: formData.value.c_day_period });
            break;
        case 'fix':
            customPopup.value.close();
            service.removeStorageSync('curSaleFormData');
            service.addlocalStorage('curSaleFormData', { c_unit_type: formData.value.c_unit_type, c_adno_level: formData.value.c_adno_level, c_class_level: formData.value.c_class_level, c_day_period: formData.value.c_day_period });
            if (formData.value.c_type == '2') {
                formData.value.c_level = formData.value.c_adno_level;
            } else if (formData.value.c_type == '3') {
                formData.value.c_level = formData.value.c_class_level;
            }

            await searchData();
            break;
    }
};


const getCurrentTimeSlot = async (hoursPerSlot = 2) => {
    const now = dayjs();
    const totalMinutes = now.hours() * 60 + now.minutes();
    const minutesPerSlot = hoursPerSlot * 60;
    const timeSlot = Math.floor(totalMinutes / minutesPerSlot);
    const startHour = timeSlot * hoursPerSlot;
    const endHour = (timeSlot + 1) * hoursPerSlot;
    return [`${startHour.toString().padStart(2, '0')}:00`, `${endHour.toString().padStart(2, '0')}:00`];
}
const clickDetail = () => {
    const { c_sale_da, c_sale_da_en, c_sale_da2, c_sale_da2_en, c_store_id, c_current_type, c_type, c_level, c_unit_type } = formData.value;
    uni.navigateTo({
        url: `./detail?c_sale_da=${c_sale_da}&c_sale_da_en=${c_sale_da_en}&c_sale_da2=${c_sale_da2}&c_sale_da2_en=${c_sale_da2_en}&c_store_id=${c_store_id}&c_current_type=${c_current_type}&c_type=${c_type}&c_level=${c_level}&c_unit_type=${c_unit_type}`,
    });
}

const buttonClick = async (e) => {
    const { singleTag, modelValue, type } = e;
    switch (singleTag) {
        case 'reset':
            formData.value = {
                ...formData.value,
                c_sale_da: dayjs().format('YYYY-MM-DD'),
                c_sale_da_en: dayjs().format('YYYY-MM-DD'),
                c_sale_da2: dayjs().subtract(1, 'days').format('YYYY-MM-DD'),//对期
                c_sale_da2_en: dayjs().subtract(1, 'days').format('YYYY-MM-DD'),//对期
            };
            break;
        case 'fix':
            searchPopup.value.close()
            await searchData();
            break;
    }
};

// 系统参数，字典
const sysConfig = ref({
    adnoLevel: [],
    gdsclassLevel: [],
    rentSaleIsRevenue: false,
})

onMounted(() => {
    getListHeight()
})

// 获取列表高度
const getListHeight = async () => {
    await uni.getSystemInfo({
        success: function (res) { // res - 各种参数
            let info = uni.createSelectorQuery().select(".footer-view");
            info.boundingClientRect(function (data) { //data - 各种参数
                //获取列表高度
                let height = res.windowHeight - data.top;
                //转换rpx
                let finalHeight = height / (res.windowWidth / 750) - 100;
                listHeight.value = finalHeight;
                oriHeight.value = finalHeight;
            }).exec()
        }
    });
};
// 点击navbar右侧图标
const clickNavbarRight = () => {
    customPopup.value.open();
}
// 选择框点击事件
const clickStore = () => {
    let parms = Enjoy.GetDialogParms();
    parms.CallBack = SelectionChanged;
    parms.SelectionType = "机构选择";
    parms.SelectedItems = sUserStore.value;
    Enjoy.OpenDialog(parms)
}

const SelectionChanged = async (event) => {
    if (event.SelectionType == '机构选择') {
        // 更新机构信息
        sUserStoreName.value = event.BackParms.Value;
        sUserStore.value = event.BackParms.Key;
        // 按新条件获取数据
        formData.value.c_store_id = sUserStore.value;
        await updateStoreType();
    }
    // 按新条件获取数据
    await searchData();
}

</script>

<style lang="scss" scoped>
@import '@/main.scss';
@import '@/static/font/enjoyicon/iconfont.css';
@import '@/static/font/menu/iconfont.css';

.content {
    background-color: #F4F4F4;
    display: flex;
    padding: 0;
    width: 100%;
}

.content-img {
    background: pink;
    background-size: 100% 150px;
    background-repeat: no-repeat;
    flex: 1;
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    align-items: stretch;
}

.navigation {
    flex: 0 0 auto;
    margin-bottom: 5px;
}

.main-view {
    width: 100%;
    height: auto;
    background: #00aaff;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.footer-view {
    width: 100%;
    flex: 1;
    box-sizing: border-box;
    margin-top: 16rpx;
    display: flex;
}

// start 重置标题栏右侧样式 展示当前用户所属门店
::v-deep .uni-navbar__header-btns-right {
    position: relative;
    height: 100%;
}

::v-deep .uni-nav-bar-right-text {
    position: absolute;
    top: 0;
    right: 0;
    color: #aaffff;
    text-align: center;
    max-width: 200rpx;
    margin-right: 30rpx;
    font-size: 0.8rem;
    padding-top: 0.1rem;
    justify-content: center;
    align-items: center;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

// end  重置标题栏右侧样式 展示当前用户所属门店

.scroll-box {
    height: 100%;
}

// 日期选择
.search-bar {
    background: #FFFFFF;
    display: flex;
    justify-content: space-around;
    flex: 0 0 auto;
    padding: 10rpx 0 0 0;

    .left,
    .right,
    .center {
        display: flex;
        align-items: flex-start;
        justify-content: space-around;
        flex-direction: column;

        // 重置日期选择组件内的显示文字大小
        ::v-deep .uni-date-x {
            background-color: transparent;
        }

        ::v-deep .uni-date__x-input {
            font-size: 32rpx !important;
            font-weight: bold;
            background: transparent;
            border-bottom: 1px solid rgba(30, 30, 30, 0.1);
        }

        checkbox-group {
            display: flex;
            flex-direction: column;
            gap: 10rpx;
            padding: 10rpx 0;
        }

        label {
            color: #626262;
        }
    }

    .left,
    .right {
        padding: 10rpx 0;

        label {
            font-size: 0.6rem;
            margin: 0;
            padding: 0;
            line-height: 1rem;
        }

    }

    .left {
        ::v-deep .uni-date__x-input {
            color: #4090f7;
        }
    }

    .right {
        ::v-deep .uni-date__x-input {
            color: #9ec87d;
        }
    }

}

// 数据展示
.data-box {
    margin: 0 20rpx 20rpx 20rpx;
    padding: 0 $uni-spacing-row-base;
    background-color: #FFFFFF;
    border-radius: 20rpx;
    display: flex;
    flex-wrap: wrap;

}

// 数据展示
.data-title {
    margin: 0 20rpx 20rpx 20rpx;
    padding: 0 $uni-spacing-row-base;
    display: flex;
    flex-wrap: wrap;

}


// 机构，部门，品类 曲线图 切换
.chart-box {
    background: #ffffff;
    padding-top: 20rpx;

    .chart-ctrl {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin: 0 20rpx;
        padding: 20rpx 0;

        .levelBox {
            flex: 0 0 25%;
            margin: 0 10rpx;
            padding: 0;
            border-bottom: 1px solid rgba(30, 30, 30, 0.1);

            ::v-deep .m-input-input-left {
                text-align: center;
                font-weight: bold;
                line-height: 1.2rem;
            }

            ::v-deep .m-card-arrowright {
                font-size: $uni-font-size-base !important;
            }
        }

        .switch-tab {
            flex: 0 0 72%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            background-color: #E3E3E3;
            padding: 6rpx;
            box-sizing: border-box;
            border-radius: 10rpx;
            height: 72rpx;

            .active,
            .normal {
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 10rpx;
                width: 50%;
                height: 100%;
                font-weight: bold;
            }

            .active {
                color: #000;
                background-color: #fff;
            }

            .normal {
                color: #515151;
            }
        }


    }

}

// 表格
.table-view {
    height: 500rpx;
    background: #ffffff;
    margin: 20rpx;
}

.table-text {
    font-size: 22rpx;
    margin: 10rpx;
}

.bottom {
    display: flex;
    justify-content: space-between;
    flex: 0 0 auto;
    height: 70rpx;
    padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
    background: $uni-bg-color;
    margin-bottom: 2px;
}


// start 自定义更多按钮
// 复制 RdsNavBar
.custom-menu {
    border-top: 1px solid rgba(0, 0, 0, .1);
    display: flex;
    flex: 1;
    width: 100%;
    justify-content: flex-start;
}

.popup-icon-btn {
    display: flex;
    padding: 10px;
    margin: 5px;
    color: #333333;
    text-align: center;
    flex-direction: column;
}

.popup-icon-btn uni-icon {
    margin: 0 auto;
    background: #ffffff;
    border-radius: 50%;
    font-size: 1.2em;
    width: 42px;
    height: 42px;
    line-height: 42px;
    text-align: center;
}

.popup-icon-btn uni-text {
    font-size: 0.8em;
    padding: 0.2em 0;
    line-height: 1.4em;
    width: 52px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

// 业务自定义
.icon_new_count {
    color: #00aaff;
}

// end 自定义更多按钮

// start 查询筛选
.search-fields {
    width: 100%;

    .center {
        margin: 0 10px;
    }

    uni-button {
        font-size: 16px;
        line-height: 40px;
    }

    .search-field {
        margin: 5px 0;
        padding: 5px 0;
        font-size: 18px;
    }

    ::v-deep .m-card-input-content,
    ::v-deep .m-input-input {
        height: 100%;
        text-align: right !important;

        uni-view,
        * {
            font-size: 16px;
            margin: 0 !important;
        }
    }

    .bottom {
        background: #ffffff;
        margin: 5px 0px 0px;
        padding: 5px 0;
        border-top: 1px solid #cccccc;
    }
}

// end 查询筛选

// 列表项自定义
.custom-id {
    z-index: 1;
    position: relative;
    line-height: 1.2em;
}

.custom-id::before {
    position: absolute;
    z-index: 0;
    content: ' ';
    width: 2.5em;
    height: 1.2em;
    background: rgba(153, 255, 102, 0.2);
    top: 0;
    left: 0;
}

// end 列表项自定义
.stylePriv1 {
    color: #333333 !important;
}

.stylePriv2 {}

.flex-item {
    flex: 1 1 50%;
}

.selector-view {
    width: 100%;
    height: auto;
    background: #FFFFFF;
    display: flex;
    flex-direction: row;
    padding: 15rpx;
}

.levelBox {
    flex: 0 0 25%;
    margin: 0 10rpx;
    padding: 0;
    border-bottom: 1px solid rgba(30, 30, 30, 0.1);

    ::v-deep .m-input-input-left {
        text-align: center;
        font-weight: bold;
        line-height: 1.2rem;
    }

    ::v-deep .m-card-arrowright {
        font-size: $uni-font-size-base !important;
    }
}

.center-view {
    width: 100%;
    height: auto;
    display: flex;
    flex-direction: row;
    background: #ffffff;
    padding: 15rpx;
}

.tips-text {
    margin-left: 20rpx;
    color: $uni-text-color-grey;
}

.item-view {
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    align-items: center;
    margin-top: 16rpx;
    row-gap: 8rpx;
}

.m-list-top {
    width: 100%;
    display: grid;
    grid-template-columns: 40% 59%;
    font-size: 12px;
}

.rate-view {
    width: 100%;
    display: grid;
    grid-template-columns: 50% 50%;
    grid-template-rows: 33.33% 33.33% 33.33%;
    font-size: 24rpx;
}

.rate-card {
    margin: 2rpx;
    border-radius: 10rpx;
    background-color: rgb(249, 249, 249);
    padding: 2rpx;
}

.rank-card {
    margin: 4rpx;
    border-radius: 10rpx;
    background-color: rgb(249, 249, 249);
    padding: 4rpx;
}


.bt-button {
    background-color: #FFFFFF;
    padding: 10rpx 0rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
}


.popup-content {
    align-items: center;
    justify-content: flex-start;
    flex-direction: column;
    padding: 0 20rpx 20rpx 20rpx;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
    // height: 600rpx;
    // overflow-y: scroll;
}


.image-min {
    width: 100%;
    height: 150rpx;
    opacity: 0.6;
    margin-top: -20rpx;
}

.no-data-text {
    text-align: center;
    color: #cccccc;
    font-size: 26rpx;
    margin-top: -20rpx;
}

.popup-height {
    width: 200px;
}

.popup-content-message {
    align-items: center;
    justify-content: left;
    flex-direction: column;
    padding: 0 20rpx 20rpx 20rpx;
    width: 600rpx;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
}

.popup-title {
    width: 100%;
    height: 84rpx;
    background: #FFFFFF;
    border-radius: 40rpx 40rpx 0 0;
    display: flex;
    justify-content: center;
    align-items: center;
    color: $uni-text-color-secondary;
    font-size: $uni-font-size-level1;
    line-height: 45rpx;
    text-align: center;
    position: relative;
}


.m-card-input-view2 {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 100%;
    height: 122rpx;
    background: $uni-bg-color-inverse;
    box-sizing: border-box;
    border-bottom: 1rpx solid #EEEEEE;
}

.m-card-input-title2 {
    width: 185rpx;
    height: 40rpx;
}

.m-title-text2 {
    font-size: $uni-font-size-level3;
    font-family: $uni-font-family;
    font-weight: $uni-font-weight-level1;
    color: $uni-text-color-title;
    line-height: 40rpx;
    text-align: left;
    font-style: normal;
}

.time-view {
    display: flex;
    flex-direction: column;
}

.time-top {
    font-size: $uni-font-size-level2;
    font-family: $uni-font-family;
    color: $uni-text-color-primary;
    line-height: 30rpx;
    text-align: left;
    font-style: normal;
}


.heng-view {
    width: 28rpx;
    height: 2rpx;
    background: $uni-text-color-weak;
    margin: 40rpx;
}

.swiper {
    height: 400rpx;
}
</style>